// 实现sum 函数
function sum(a) {
  if (sum.res == undefined) {
    sum.res = 0;
  }
  sum.res = sum.res + a;
  return sum;
}

console.log(sum(5)(10)(20));

// 使用函数柯里化
function add(...arg) {
  const sum = (...args) => {
    let result = 0;
    for (let i = 0; i < args.length; i++) {
      result += args[i];
    }
    return result;
  };

  let res = sum(...arg);
  const addResult = (...args) => {
    res = res + sum(...args);
    return addResult;
  };
  addResult.toString = function () {
    return res;
  };
  return addResult;
}

// 实现 add 函数
function add(...arg) {
  const sum = (...args) => {
    let result = 0;
    for (let i = 0; i < args.length; i++) {
      result += args[i];
    }
    return result;
  };

  let res = sum(...arg);
  const addResult = (...args) => {
    if (args.length > 0) {
      res = res + sum(...args);
      return addResult;
    } else {
      return res;
    }
  };

  return addResult;
}

console.log(add(1)());
console.log(add(1, 2, 3)(4)());
console.log(add(1)(2)(3)(4)(5)());

// 3种调用方式，toString ,fn.res , () 获得最终结果
